package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {

    /**
     * 获取静态资源文件的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath().substring(1);
        return absolutePath.substring(0, absolutePath.length()-1) + path;
    }

    /**
     * 读取静态资源文件输入流，通过输出流输出
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        //静态资源文件长度
        int resourceSize = count;
        //先输出请求头信息，再输出静态资源信息
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        //读取静态资源内容进行输出
        //已经读取的内容长度
        int written = 0;
        //计划每次缓冲的长度
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];

        while (written < resourceSize) {
            //当已读取的内容长度 + 单次缓冲读取的内容长度 > 静态文件总内容长度时，按实际长度进行读取
            if (written + byteSize > resourceSize) {
                //实际剩余内容长度
                byteSize = resourceSize - written;
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written += byteSize;
        }
    }
}
